<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="70px">
        <el-form-item label="生产日期">
          <el-date-picker
            v-model="searchParam.planDateSearch"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="getplanDate"
          />
        </el-form-item>
        <el-form-item label="产品">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请选择产品"
            clearable
            readonly
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button @click="resetMaterial"> 清除 </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="计划状态">
          <el-select
            v-model="searchParam.planStatus"
            placeholder="请选择计划状态"
            clearable
          >
            <el-option
              v-for="item in useDictionary('ProduceOrderState')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <!--<el-button type="primary" plain @click="adjustOrder()"
          >生产顺序调整</el-button
        >-->
        <el-button type="primary" plain @click="command()">下达</el-button>
        <el-button type="primary" plain @click="probe()"
          >日计划班制查看</el-button
        >
        <el-button
          class="ml-3"
          @click="
            useDownload('/mes/mesdayplan/export', '日生产计划', searchParam)
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
        <el-button type="primary" plain @click="restperiod()"
          >休息日期设置</el-button
        >
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        :max-height="tableHeight"
        border
        @selection-change="handleSelectionChange"
      >
        <template v-for="item in tableColumns" :key="item">
          <TableColumn v-if="item.prop && item.isShow" :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope"></slot>
            </template>
          </TableColumn>
        </template>
        <!--<el-table-column type="selection" width="55" align="center" />-->
        <!-- <el-table-column
          label="生产计划编号"
          prop="producePlanCode"
          min-width="130"
          show-overflow-tooltip
        />
        <el-table-column
          label="产品名称"
          prop="materialName"
          min-width="155"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column
          label="日生产计划号"
          prop="planNum"
          min-width="125"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="日计划生成顺序"
          prop="workSequence"
          min-width="120"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="设备"
          prop="stoveNum"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="班次"
          prop="shiftName"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          label="生产日期"
          prop="planDate"
          min-width="100"
          show-overflow-tooltip
          align="center"
          :formatter="formatDate"
        />
        <el-table-column
          label="数量"
          prop="planQuantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="计划状态"
          prop="planStatus"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("ProduceOrderState", scope.row.planStatus) }}
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="创建人"
          prop="createdUserName"
          min-width="100"
          show-overflow-tooltip
        />
        <el-table-column
          label="更新时间"
          prop="lastUpdateTime"
          min-width="160"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="更新人"
          prop="lastUpdatedUserName"
          min-width="100"
          show-overflow-tooltip
        /> -->
        <el-table-column fixed="right" label="操作" width="100" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="productionVersion(scope.row)"
              >生产版本</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[100, 10, 25, 50]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesdayplan-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <!--物料选择-->
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
    <mesdayplan-adjustOrder
      :visible="adjustDialog.visible"
      :title="adjustDialog.title"
      :data="adjustDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="adjustDialog.readvisible"
      @change-visible="changeVisibleAdjust"
    />
    <mesdayplan-allocatingOrder
      :visible="allocatingDialog.visible"
      :title="allocatingDialog.title"
      :data="allocatingDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="allocatingDialog.readvisible"
      @change-visible="changeVisibleAllocating"
    />
    <dayPlanProductionVersionEdit
      :visible="productionVersionDialog.visible"
      :title="productionVersionDialog.title"
      :data="productionVersionDialog.data"
      @reset-table="(id:string) => (getTableList())"
      :is-readonly="productionVersionDialog.readvisible"
      @change-visible="changeProductionVersion"
    />
    <mesdayplan-command
      :visible="commandDialog.visible"
      :title="commandDialog.title"
      :data="commandDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="commandDialog.readvisible"
      @change-visible="changeVisibleCommand"
    />
    <mesdayplan-view
      :visible="probeDialog.visible"
      :title="probeDialog.title"
      :data="probeDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="probeDialog.readvisible"
      @change-visible="changeVisibleProbe"
    />
    <restperiod-edit
      :visible="restperiodDialog.visible"
      :title="restperiodDialog.title"
      :data="restperiodDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="restperiodDialog.readvisible"
      @change-visible="changeVisibleRestperiod"
    />

    <!-- 列设置 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    />
  </div>
</template>

<script setup lang="ts">
import {
  useTable,
  useDownload,
  useDictionary,
  useComputeTableHeight,
} from "@/utils/useTable";
import request from "@/utils/request";
import { productionVersionHook } from "@/views/mes/mesdayplan/hook/productionVersionHook";
import useEvent from "@/utils/useEvent";
defineOptions({
  name: "MESMESDAYPLAN",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesdayplan/queryByPage";
const { api } = productionVersionHook();
// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  materialId: "",
  materialCode: "",
  planDateSearch: [],
  planDateStart: "",
  planDateEnd: "",
  planStatus: "",
};

const deleteParam = {
  api: "/mes/mesdayplan/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam,
  100
);

const tableHeight = ref<any>("auto");
onMounted(() => {
  getTableList();
  setTimeout(() => {
    tableHeight.value = useComputeTableHeight();
  }, 100);
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
const adjustDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
const allocatingDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
const productionVersionDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
/** 打开生产顺序调整弹窗 */
function adjustOrder() {
  adjustDialog.title = "生产顺序调整";
  adjustDialog.visible = true;
  adjustDialog.readvisible = false;
}
function changeVisibleAdjust(value: boolean) {
  adjustDialog.visible = value;
  if (!value) {
    adjustDialog.data = {};
  }
}
/** 打开生产顺序调整弹窗 */
function allocatingOrder(row: any) {
  allocatingDialog.title = "下达";
  getInfo(row.id);
}
function changeVisibleAllocating(value: boolean) {
  allocatingDialog.visible = value;
  if (!value) {
    allocatingDialog.data = {};
  }
}
// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesdayplan/get/${id}`,
    method: "get",
  })
    .then((data) => {
      allocatingDialog.data = data.data;
      allocatingDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

function productionVersion(row: any) {
  productionVersionDialog.title = "生产版本";
  getProductionVersion(row);
}
function changeProductionVersion(value: boolean) {
  productionVersionDialog.visible = value;
  if (!value) {
    productionVersionDialog.data = {};
  }
}
async function getProductionVersion(row: any) {
  const { data } = await request({
    url: `${api.getDayVersionList}`,
    method: "post",
    data: { planDayId: row.producePlanCode },
  });
  data[0].planDayId = row.producePlanCode;
  productionVersionDialog.data = data[0];
  // if (row.planStatus != 0) {
  //   productionVersionDialog.readvisible = true;
  // }
  productionVersionDialog.visible = true;
}
// 查询详情
async function getEditItem(id: string) {
  const { data } = await request({
    url: `${api.get}/${id}`,
    method: "get",
  });
  return data;
}
/** 打开日生产计划表表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改日生产计划表";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增日生产计划表";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开日生产计划表表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "日生产计划表详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

function getplanDate(data: any) {
  if (data) {
    searchParam.value.planDateStart = data[0];
    searchParam.value.planDateEnd = data[1];
  } else {
    searchParam.value.planDateStart = "";
    searchParam.value.planDateEnd = "";
  }
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/mesdayplan/deleteItem/${id}`,
      method: "post",
    });
    search();
  });
}
//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
//产品选择
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.value.materialId = data.id;
    searchParam.value.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const resetMaterial = () => {
  searchParam.value.materialId = "";
  searchParam.value.materialCode = "";
};

const commandDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

const probeDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

function command() {
  commandDialog.title = "下达";
  commandDialog.visible = true;
}

function changeVisibleCommand(value: boolean) {
  commandDialog.visible = value;
  if (!value) {
    commandDialog.data = {};
  }
}

function changeVisibleProbe(value: boolean) {
  probeDialog.visible = value;
  if (!value) {
    probeDialog.data = {};
  }
}

function probe() {
  probeDialog.title = "日计划班制查看";
  probeDialog.visible = true;
}

const restperiodDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

function restperiod() {
  restperiodDialog.title = "休息日期设置";
  restperiodDialog.visible = true;
}

function changeVisibleRestperiod(value: boolean) {
  restperiodDialog.visible = value;
  if (!value) {
    restperiodDialog.data = {};
  }
}

const tableColumns = reactive([
  {
    prop: "producePlanCode",
    label: "生产计划编号",
    minWidth: 130,
    isShow: true,
    align: "left",
  },
  {
    prop: "materialName",
    label: "产品名称",
    minWidth: 155,
    isShow: true,
    align: "left",
  },
  {
    prop: "planNum",
    label: "日生产计划号",
    minWidth: 125,
    isShow: true,
    align: "center",
  },
  {
    prop: "workSequence",
    label: "日计划生成顺序",
    minWidth: 120,
    isShow: true,
    align: "center",
  },
  {
    prop: "stoveNum",
    label: "设备",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "shiftName",
    label: "班次",
    minWidth: 150,
    isShow: true,
    align: "left",
  },
  {
    prop: "planDate",
    label: "生产日期",
    minWidth: 100,
    isShow: true,
    align: "center",
    formatter: formatDate,
  },
  {
    prop: "planQuantity",
    label: "数量",
    minWidth: 100,
    isShow: true,
    align: "right",
    headerAlign: "center",
  },
  {
    prop: "planStatus",
    label: "计划状态",
    minWidth: 100,
    isShow: true,
    align: "center",
    render: (scope: any) =>
      useDictionary("ProduceOrderState", scope.row.planStatus),
  },
  {
    prop: "createTime",
    label: "创建时间",
    minWidth: 160,
    isShow: true,
    align: "center",
  },
  {
    prop: "createdUserName",
    label: "创建人",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
  {
    prop: "lastUpdateTime",
    label: "更新时间",
    minWidth: 160,
    isShow: true,
    align: "center",
  },
  {
    prop: "lastUpdatedUserName",
    label: "更新人",
    minWidth: 100,
    isShow: true,
    align: "left",
  },
]);

const searchColumns = reactive([]);
</script>
